package com.fw.service.impl;

import java.sql.SQLException;
import java.util.List;

import com.fw.dao.UserDao;
import com.fw.dao.impl.UserDaoImpl;
import com.fw.model.Permission;
import com.fw.model.Role;
import com.fw.model.User;
import com.fw.service.UserService;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;

public class UserServiceImpl implements UserService {
	UserDao userDao = null;
	@Override
	public User query_userByUNameAndUPwdService(User user) {
		userDao = new UserDaoImpl();
		User u = userDao.query_userByUNameAndUPwdDao(user);
		return u;
	}
	@Override
	public Integer query_totalUserService(String sql) {
		userDao = new UserDaoImpl();
		Integer count = userDao.query_totalUserDao(sql);
		return count;
	}
	@Override
	public List<User> query_allUserByPageService(String sql, int firstPage,int maxPage) {
		userDao = new UserDaoImpl();
		List<User> users = userDao.query_allUserByPageDao(sql, firstPage, maxPage);
		return users;
	}
	@Override
	public boolean delete_userByIdService(User user) {
		userDao = new UserDaoImpl();
		boolean flag = userDao.delete_userByIdDao(user);
		return flag;
	}
	@Override
	public boolean add_userService(User user){
		userDao = new UserDaoImpl();
		final User u1 = user;
		boolean f = Db.tx(new IAtom() {
			@Override
			public boolean run() throws SQLException {
				User u = userDao.query_userByEmailDao(u1);
				if(u != null) return false;
				boolean flag = userDao.add_userDao(u1);
				return flag;
			}
		});
		return f;
	}
	@Override
	public boolean update_userService(User user) {
		userDao = new UserDaoImpl();
		return userDao.update_userByIdDao(user);
	}
	@Override
	public User query_userByIdService(User user) {
		userDao = new UserDaoImpl();
		return userDao.query_userByIdDao(user);
	}
	@Override
	public Role query_roleByUserService(User user) {
		List<Role> rs = user.getRoles();
		if(rs != null && rs.size() > 0) return rs.get(0);
		return null;
	}
	@Override
	public boolean update_roleByUserService(User user,Role role) {
		userDao = new UserDaoImpl();
		return userDao.update_userRoleDao(user,role);
	}
	@Override
	public boolean userIsPermissionService(User user, Permission permisson) {
		userDao = new UserDaoImpl();
		return userDao.userIsPermissionDao(user, permisson);
	}
	@Override
	public boolean update_user_pwdService(User user) {
		userDao = new UserDaoImpl();
		boolean flag = userDao.update_user_pwdDao(user);
		return flag;
	}
}
